import { baseRouter } from "@/router/baseRouter.js";
import { authorityRouter } from "@/router/authorityRouter.js";
import _ from "lodash";

/**
 * 获取用户的授权页面
 * @param  {Array} fns             用户拥有的功能列表
 * @param  {Array} authorityRouter 所有路由列表
 * @return {[type]}                 [description]
 */
function getRouters(fns, authorityRouter) {
  const authorityRouters = [];

  authorityRouter.forEach(item => {
    if (hasFns(fns, item)) {
      var obj = item;
      if (item.children && item.children.length) {
        var child = getRouters(fns, item.children);
        if (child && child.length) {
          obj.children = child;
        } else {
          delete obj.children;
        }
      }
      authorityRouters.push(obj);
    }
  });

  return authorityRouters;
}
/**
 * 判断是否有功能权限
 * @param  {Array}  fns   用户自己的功能节点
 * @param  {[type]}  route 当前路由
 * @return {Boolean}       [description]
 */
function hasFns(fns, route) {
  if (route.meta && route.meta.fn && route.meta.fns) {
    for (let i = fns.length; i--; ) {
      if (_.indexOf(route.meta.fns, fns[i]) >= 0) {
        return true;
      }
    }
    return false;
  } else {
    return true;
  }
}

// 把所有vue的路由拆成平铺方式
function setOffspringFn(data) {
  for (let i = data.length; i--; ) {
    let fns = [];
    if (data[i].meta && data[i].meta.fn) {
      fns.push(data[i].meta.fn);

      if (data[i].children && data[i].children.length) {
        const childFns = getChildrenFn(data[i].children);
        fns = fns.concat(childFns);
        data[i].children = setOffspringFn(data[i].children);
      }

      data[i].meta.fns = fns;
    }
  }

  return data;
}

// 为自己获取所有子级节点
function getChildrenFn(children) {
  const arr = [];
  for (let i = children.length; i--; ) {
    if (children[i].meta && children[i].meta.fn) {
      arr.push(children[i].meta.fn);
    }

    if (children.children && children.children.length) {
      arr.concat(getChildrenFn(children.children));
    }
  }
  return arr;
}

const state = {
  routes: [], // 所有生成的routes
  addRoutes: [] // 后面根据权限生成的routes
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = baseRouter.concat(routes);
  }
};

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // const accessedRoutes
      let arrAuthorityRouter = _.cloneDeep(authorityRouter);

      const newAuthorityRouter = setOffspringFn(arrAuthorityRouter);
      // // const newAuthorityRouter = {}
      const accessedRoutes = getRouters(roles, newAuthorityRouter);
      commit("SET_ROUTES", accessedRoutes);
      // resolve({});
      resolve(accessedRoutes);
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
